﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Json;
using Common;

namespace WebManager
{
    public partial class ChildWindow1 : ChildWindow
    {
        public bool IsOpenMode
        {
            get;
            set;
        }

        WebManager.Views.Account accountPage = null;
        public UploadStringCompletedEventHandler uploadStringCompleted;
        System.Collections.ObjectModel.ObservableCollection<Contract> itemSource = new System.Collections.ObjectModel.ObservableCollection<Contract>();

        public ChildWindow1(WebManager.Views.Account page)
        {
            this.accountPage = page;
            InitializeComponent();
            this.btnSvcDel.Click += new RoutedEventHandler(btnSvcDel_Click);
            this.dataGrid.ItemsSource = itemSource;
            uploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
        }

        void btnSvcDel_Click(object sender, RoutedEventArgs e)
        {
            Contract row = this.dataGrid.SelectedItem as Contract;
            if (row != null)
            {
                if (this.itemSource.Contains(row))
                    itemSource.Remove(row);
            }   
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            Save();
            
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void btnSvcAdd_Click(object sender, RoutedEventArgs e)
        {
            string vendor = "";
            string serviceName = "전용서비스";
            string serviceCode = "0003";
            string beginDate = System.DateTime.Now.ToString("yyyyMMddHHmmss");

            System.Globalization.Calendar myCal = System.Globalization.CultureInfo.InvariantCulture.Calendar;
            string endDate = myCal.AddMonths(System.DateTime.Now, 1).ToString("yyyyMMddHHmmss");

            if (this.comboBox1.SelectedIndex == 1)
            {
                serviceName = "시스템서비스";
                serviceCode = "0001";
                endDate = "99991231235959";
                vendor = "system";
            }

            Contract contract = new Contract();
            contract.ServiceInfo = new Service() { ServiceCode = serviceCode, ServiceName = serviceName };
            contract.BeginDate = beginDate;
            contract.EndDate = endDate;
            contract.Vendor = vendor;
            itemSource.Add(contract);
        }

        private void Save()
        {
            if (this.tbID.Text == string.Empty)
            {
                MessageBox.Show("ID를 입력하세요");
                this.tbID.Focus();
                return;
            }

            if (this.tbName.Text == string.Empty)
            {
                MessageBox.Show("이름을 입력하세요");
                this.tbName.Focus();
                return;
            }

            if (this.passwordBox.Password == string.Empty)
            {
                MessageBox.Show("패스워드를 입력하세요");
                this.passwordBox.Focus();
                return;
            }

            if (IsOpenMode)
            {
                // 수정
            }
            else
            {
                if (itemSource.Count == 0)
                {
                    MessageBox.Show("서비스를 추가 하세요");
                    this.passwordBox.Focus();
                    return;
                }

                // 신규
                JsonObject jObject = new JsonObject(null);
                jObject.Add("acct_id", this.tbID.Text);
                jObject.Add("acct_nm", this.tbName.Text);
                jObject.Add("acct_type", (this.comboBox1.SelectedIndex == 0)?"0001":"0002");
                jObject.Add("pwd", this.passwordBox.Password);

                JsonValue[] jValues = { };
                JsonArray jArray = new JsonArray(jValues);
                jObject.Add("contract", jArray);
                foreach (Contract contract in itemSource)
                {
                    JsonObject jObject2 = new JsonObject(new DateTimeOffset());
                    jArray.Add(jObject2);

                    jObject2.Add("svc_cd", contract.ServiceInfo.ServiceCode);
                    jObject2.Add("phone_id", contract.Phone);
                    jObject2.Add("aval_st_dt", contract.BeginDate);
                    jObject2.Add("aval_end_dt", contract.EndDate);
                    jObject2.Add("vendor", contract.Vendor);
                }
                CommonAPI.InvokeWebAPIByPost(uploadStringCompleted, "create_account", jObject.ToString(), null);
            }
        }

        protected void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Result result = CommonAPI.GetResut(e.Result);
                if (!result.result)
                {
                    // Error 처리
                    //SL_Meta.Ctrls.MainPage.msgBox.ShowMsgBox(result.error);
                    return;
                }

                if (result.command == "create_account")
                {
                    MessageBox.Show("계정이 추가되었습니다.");
                    this.accountPage.ReloadAccount();
                    this.DialogResult = true;
                }

            }
        }

        private void AcctType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (itemSource != null)
            {
                itemSource.Clear();
            }
        }
    }

    public class BeginDateFormatter : IValueConverter
    {
        // This converts the DateTime object to the string to display.
        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            // Retrieve the format string and use it to format the value.
            string formatString = parameter as string;
            if (!string.IsNullOrEmpty(formatString))
            {
                return string.Format(culture, formatString, value);
            }
            // If the format string is null or empty, simply call ToString()
            // on the value.
            return value.ToString();
        }

        // No need to implement converting back on a one-way binding 
        public object ConvertBack(object value, Type targetType,
            object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return "Error";

            DateTime dt = (DateTime)value;
            if (dt == null)
                return "Error";

            return dt.ToString("yyyyMMdd000001");
        }
    }

    public class EndDateFormatter : IValueConverter
    {
        // This converts the DateTime object to the string to display.
        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            // Retrieve the format string and use it to format the value.
            string formatString = parameter as string;
            if (!string.IsNullOrEmpty(formatString))
            {
                return string.Format(culture, formatString, value);
            }
            // If the format string is null or empty, simply call ToString()
            // on the value.
            return value.ToString();
        }

        // No need to implement converting back on a one-way binding 
        public object ConvertBack(object value, Type targetType,
            object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return "Error";

            DateTime dt = (DateTime)value;
            if (dt == null)
                return "Error";

            return dt.ToString("yyyyMMdd235959");
        }
    }

    public class Service
    {
        public string ServiceCode
        {
            get;
            set;
        }

        public string ServiceName
        {
            get;
            set;
        }
    }

    public class Contract
    {
        public Service ServiceInfo
        {
            get;
            set;
        }

        public string Phone
        {
            get;
            set;
        }

        public string Vendor
        {
            get;
            set;
        }

        public string BeginDate
        {
            get;
            set;
        }

        public string EndDate
        {
            get;
            set;
        }

    }

    public class ServiceProvider
    {
        public List<Service> ServiceList
        {
            get
            {
                return new List<Service> { new Service() { ServiceCode ="0001", ServiceName="시스템서비스"},  
                                    new Service() { ServiceCode ="0002", ServiceName="교환기서비스"},   
                                    new Service() { ServiceCode ="0003", ServiceName="전용서비스"},  
                                    new Service() { ServiceCode ="0004", ServiceName="SMS서비스"} };
            }
        }
    }

    public class PhoneProvider
    {
        public UploadStringCompletedEventHandler uploadStringCompleted;

        List<string> phoneList = new List<string>();
        public List<string> PhoneList
        {
            get
            {
                return this.phoneList;
            }
        }

        public PhoneProvider()
        {
            uploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
            CommonAPI.InvokeWebAPIByPost(uploadStringCompleted, "", "get_phone_list", null);
        }

        protected void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Result result = CommonAPI.GetResut(e.Result);
                if (!result.result)
                {
                    // Error 처리
                    //SL_Meta.Ctrls.MainPage.msgBox.ShowMsgBox(result.error);
                    return;
                }

                if (result.data == null || result.data == "")
                    return;

                JsonObject jObject = (JsonObject)JsonObject.Parse(result.data);
                if (!jObject.ContainsKey("recordset"))
                    return;
                JsonArray jArray = (JsonArray)jObject["recordset"];
                for (int i = 0; i < jArray.Count; i++)
                {
                    JsonArray jSubArray = (JsonArray)jArray[i];
                    if (jSubArray.Count > 0)
                        this.phoneList.Add(jSubArray[0].ToString().Replace("\"", ""));
                }
            }
        }
    }

    public class VendorProvider
    {
        public UploadStringCompletedEventHandler uploadStringCompleted;

        List<string> vendorList = new List<string>();
        public List<string> VendorList
        {
            get
            {
                return this.vendorList;
            }
        }

        public VendorProvider()
        {
            uploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
            CommonAPI.InvokeWebAPIByPost(uploadStringCompleted, "", "get_vendor_list", null);
        }

        protected void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Result result = CommonAPI.GetResut(e.Result);
                if (!result.result)
                {
                    // Error 처리
                    //SL_Meta.Ctrls.MainPage.msgBox.ShowMsgBox(result.error);
                    return;
                }

                if (result.data == null || result.data == "")
                    return;

                JsonObject jObject = (JsonObject)JsonObject.Parse(result.data);
                if (!jObject.ContainsKey("recordset"))
                    return;
                JsonArray jArray = (JsonArray)jObject["recordset"];
                for (int i = 0; i < jArray.Count; i++)
                {
                    JsonArray jSubArray = (JsonArray)jArray[i];
                    if (jSubArray.Count > 0)
                        this.vendorList.Add(jSubArray[0].ToString().Replace("\"", ""));
                }
            }
        }
    }
}

